<template>
<div>
    <el-header class="el-header">
      <el-row :gutter="24" class="el-row">
        <el-col :span="6"><el-input v-model.trim="page.phone" placeholder="请输入手机号"></el-input></el-col>
        <el-col :span="6"><el-input v-model.trim="page.nickname" placeholder="请输入用户昵称"></el-input></el-col>
        <el-col :span="6"><el-input v-model.trim="page.sex" placeholder="请输入性别"></el-input></el-col>
        <el-col :span="3"><el-button type="primary" icon="el-icon-search" @click="getUserList">搜索</el-button></el-col>
        <el-col :span="3"><el-button type="primary" icon="el-icon-plus" @click="addUser">增加用户</el-button></el-col>
      </el-row>
    </el-header>
      <table-list :table-data="userList" :columns="userListColums" @edit="editUser" @delete="deleteUser"
                  :page="page" @pageChange="pageChange" @addBtn="addUser" @editPwd='editUserPwd' @roleUser="userRole">
      </table-list>
  <!--弹窗-->
  <el-drawer :title="this.userForm.id?'修改':'添加'" v-model="dialogVisible" width="30%">
    <el-form :model="userForm" class="el-form" ref="userFormRef" :rules="userFormRules" label-width="100px">
      <el-form-item label="手机号" prop="phone" v-if="!userForm.id">
        <el-input v-model="userForm.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password" v-if="!userForm.id">
        <el-input v-model="userForm.password"></el-input>
      </el-form-item>
    <el-form-item label="姓名" prop="realname">
      <el-input v-model="userForm.realname"></el-input>
    </el-form-item>
    <el-form-item label="昵称" prop="nickname">
      <el-input v-model="userForm.nickname"></el-input>
    </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-input v-model="userForm.sex"></el-input>
      </el-form-item>
      <el-form-item label="头像" prop="headImg">
        <el-input v-model="userForm.headImg"></el-input>
      </el-form-item>
      <el-form-item label="出生日期" prop="dateOfBirth" v-if="!userForm.id">
        <el-input v-model="userForm.dateOfBirth"></el-input>
      </el-form-item>
      <el-form-item label="详细地址" prop="addressDetail">
        <el-input v-model="userForm.addressDetail"></el-input>
      </el-form-item>
    </el-form>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="sureUserDialog('userFormRef')">确 定</el-button>
  </el-drawer>
  <!-- 修改密码 -->
  <el-drawer
    title="修改密码" v-model="pwdDrawer">
    <el-form ref="pwdFormRef" :model="pwdForm" label-width="80px" :rules="pwdRules">
      <el-form-item label="用户账号" prop="nickname">
        <el-input v-model="pwdForm.nickname" disabled></el-input>
      </el-form-item>
      <el-form-item label="旧密码" prop="oldpwd">
        <el-input v-model="pwdForm.oldpwd"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newpwd">
        <el-input v-model="pwdForm.newpwd"></el-input>
      </el-form-item>
    <el-button @click="pwdDrawer = false">取 消</el-button>
    <el-button type="primary" @click="subEditPwd('pwdFormRef')">确 定</el-button>
    </el-form>
  </el-drawer>
  <!-- 给用户分配角色 -->
  <el-drawer v-model="RoleUserDrawer" title="角色分配">
    <el-table
      row-key="code"
      ref="multipleTable"
      :data="roleList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection"></el-table-column>
      <el-table-column prop="code" label="代码"></el-table-column>
      <el-table-column prop="discribe" label="描述"></el-table-column>
    </el-table>
    <el-button size="small" @click="reste">取消</el-button>
    <el-button size="small" type="primary" @click="userRoleBtn">提交</el-button>
  </el-drawer>

</div>
</template>

<script>
import PagePagination from "../../components/PagePagination";
import TableList from '../../components/tableList'
import DrawerList from '../../components/system/drawerList.vue';
import DrawerTree from "../../components/system/drawerTree";
export default {
  name: "User",
  components: {DrawerTree, DrawerList, PagePagination, TableList},
  data() {
    return {
      userList: [],
      inline: Boolean,
      page: {
        id:'',
        sex:'',
        nickname:'',
        phone:null,
        pageNo: 1,
        pageSize: 10,
        count: null,//总条数
      },
      showPwd: false,//修改页面不展示密码
      disable:true,//修改页面不能修改手机号
      userForm: {
        id:'',
        roleCode: '',
        password:  '',
        realname: '',
        sex: '男',
        nickname: '',
        phone: '',
        emall: '',
        idno: '',
        addressDetail: '',
        headImg: '',//头像
        dateOfBirth: ''
      },
      userDlist:[
        {id: 'nickname', label: '昵称',prop: 'nickname'},
        {id: 'phone', label: '手机号',prop: 'phone',},
        {id: 'password', label: '密码',prop: 'password',},
        {id: 'realname', label: '姓名',prop: 'realname',},
        {id: 'sex', label: '性别',prop: 'sex',},
        {id: 'headImg', label: '头像',prop: 'headImg',},
        {id: 'dateOfBirth', label: '出生日期',prop: 'dateOfBirth',},
        {id: 'addressDetail', label: '地址',prop: 'addressDetail',},
      ],
      dialogVisible: false,//弹出框是否显示
      userListColums: [
        {id: 'selection',  type: 'selection'},
        {id: 'index', label: '序号', type: 'index'},
        {id:'phone', label: '手机号',  prop: 'phone'},
        {id:'nickname', label: '昵称', prop: 'nickname'},
        {id:'realname', label: '姓名',  prop: 'realname'},
        {id:'sex', label: '性别', prop: 'sex'},
        {id: 'dateOfBirth', label: '出生日期',prop: 'dateOfBirth',},
        {id: 'addressDetail', label: '地址',prop: 'addressDetail',},
        {id:'state', label: '状态', prop: 'state'},
        {id:'button', label: '操作', type: 'button', list: [
            {id:'edit', label: '修改用户信息', type: 'text'},
            {id:'editPwd', label: '修改密码', type: 'text'},
            {id:'delete', label: '删除', type: 'text'},
            {id:'roleUser', label: '分配角色', type: 'text'},
          ]},
      ],
      userFormRules: {
        phone: [{required: true, message: '请输入手机号', trigger: 'blur'},],
        nickname: [{required: true, message: '请输入昵称', trigger: 'blur'},],
        password: [{required: true, message: '请输入密码', trigger: 'blur'},],
        realname: [{required: true, message: '请输入姓名', trigger: 'blur'},],
      },
      pwdDrawer: false,
      pwdForm: {
        id: '',
        nickname: '',
        oldpwd: '',
        newpwd: '',
      },
      RoleUserDrawer: false,
      pwdRules: {
        oldpwd: [{required: true, message: '请输入旧密码', trigger: 'blur'},],
        newpwd: [{required: true, message: '请输入新密码', trigger: 'blur'},
                {min: 6, max: 20, message: '密码最少6位，最多20位', trigger: 'blur',},
        ],
      },
      roleList: [],//保存角色列表数据
      userRoleList: [],//保存当前用户的角色
      RoleUser: [],//用来存储选中的角色code
      userId:null,//当前点击的用户id
  }
    },
  created() {
    this.getUserList();
    this.getRoleList();
  },
  methods: {
    pageChange(val) {
      this.page.pageSize = val.pageSize;
      this.page.pageNo = val.pageNo;
      this.getUserList()
    },

    async getRoleList() {
      await this.$api.system.getRoleList().then(res => {
        if (res.status === 200)
          this.roleList = res.data.data;
        console.log('122012212===', this.roleList)
      })
    },
    getUserList() {
      let par = {
        sex:this.page.sex,
        phone:this.page.phone,
        realname:this.page.realname,
        pageNo:this.page.pageNo,
        pageSize: this.page.pageSize
      };
      this.$api.system.getUserList(par).then(res => {
        console.log(res)
        this.userList = res.data.data;
        this.page.count = res.data.count;
      })
    },
//增加
    addUser() {
      this.userForm = {}
      this.dialogVisible = true;
    },
//修改
    editUser(val) {
      this.dialogVisible = true;
      this.userForm.id = val.id;
        let par ={
          id: val.id
        }
      console.log(val.id)
        this.$api.system.getUser(val.id,par).then(res => {
          if (res.data.code ===200){
            this.dialogVisible = true
            this.userForm = res.data.data
          }
        })
    },
    //修改密码
    editUserPwd(val) {
      this.pwdForm = {};
      this.pwdForm.nickname = val.nickname;
      this.pwdForm.id = val.id;
      this.pwdDrawer = true;
      console.log(this.pwdForm.id)
    },
    subEditPwd(pwdForm) {
      this.$refs[pwdForm].validate((valid) =>{
        if(valid) {
          let par = {
            id: this.pwdForm.id,
            oldpwd: this.pwdForm.oldpwd,
            newpwd: this.pwdForm.newpwd,
          };
            this.$api.system.editUserPwd(par).then(res =>{
            console.log(res.data);
             if(res.status === 200) {
               this.$message.success('修改成功');
             }else {
               this.$message.error(res.data.message);
             }
          }).catch(err => {})
        }
      })
    },
    //删除
    deleteUser(val) {
      this.$confirm('是否删除？','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res => {
        let par = val.id;
          this.$api.system.deleteUser(par).then(res=>{
            if(res.data.code === 200) {
              this.$message.success('删除成功')
              this.getUserList()
            }else {
              this.$message.error('删除失败')
           }
          })

      }).catch(error => {
        this.$message.error('删除错误')
      })
    },
//弹窗中的提交按钮
    async sureUserDialog(formName) {
      await this.$refs[formName].validate((valid) => {
        if (valid) {
          const id=this.userForm.id;
          console.log(id);
          if (id == null || id ==='') {
            this.$api.system.addUser(this.userForm).then(res => {
              if (res.data.code !== 200) {
                this.$message.error(res.data.message)
              } else {
                this.$message.success('成功');
                this.dialogVisible = false;
                this.getUserList()
              }
            });
          } else {
            this.$api.system.getEditUser(this.userForm).then(res => {
              console.log('这里是res.status=', res.data.code );
              if (res.data.code !== 200) {
                this.$message.error('修改失败')
              } else {
                this.getUserList();
                this.dialogVisible = false;
                this.$message.success('修改信息成功');
              }
            });
          }
        }else{
          console.log('error submit!!');
          return false;
        }
      });
    },
    //分配角色
    userRole(val) {
      this.RoleUser = [];
      console.log('分配角色');
      console.log(val.id);
      this.userId = val.id;
      let par = {
        userId: this.userId,
        pageNo: 1,
        pageSize: 100
      }
      this.$api.system.getUserRoleList(par).then(res => {
        if (res.status === 200) {
          console.log(res.data.data)
          this.userRoleList = res.data.data;
          this.RoleUser = [];
          this.RoleUserDrawer = true;
        }
      }).catch()

    },
    handleSelectionChange(data) {
      console.log(data);
      let arr = [];
      for(let i=0;i<data.length;i++){
        let item = data[i];
        arr.push(item.code);
      }
      let rodeCodes = arr.join(',')
      this.RoleUser = rodeCodes
      console.log(this.RoleUser);
    },
    userRoleBtn() {
      var par = {
        userId:this.userId,
        rodeCodes: this.RoleUser,
      }
      console.log('userb===', par)
    },
    reste() {
      this.RoleUserDrawer = false;
    }
  }
}
</script>

<style scoped>
.el-header {
  --el-header-padding: 0 20px;
  --el-header-height: 60px;
  padding: var(--el-header-padding);
  box-sizing: border-box;
  flex-shrink: 0;
  height: var(--el-header-height);
  margin-bottom: 10px;
}
</style>